package io.jenkins.plugins;

import hudson.Util;
import hudson.remoting.VirtualChannel;
import jenkins.MasterToSlaveFileCallable;
import org.apache.tools.ant.types.FileSet;

import javax.annotation.Nonnull;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

class ListFiles extends MasterToSlaveFileCallable<Map<String, String>> {
    private static final long serialVersionUID = 1;
    private final String includes, excludes;
    private final boolean defaultExcludes;
    private final boolean caseSensitive;

    ListFiles(@Nonnull String includes, @Nonnull String excludes, boolean defaultExcludes, boolean caseSensitive) {
        this.includes = includes;
        this.excludes = excludes;
        this.defaultExcludes = defaultExcludes;
        this.caseSensitive = caseSensitive;
    }

    @Override public Map<String,String> invoke(@Nonnull File basedir, VirtualChannel channel) throws IOException, InterruptedException {
        Map<String,String> r = new HashMap<>();

        FileSet fileSet = Util.createFileSet(basedir, includes, excludes);
        fileSet.setDefaultexcludes(defaultExcludes);
        fileSet.setCaseSensitive(caseSensitive);

        for (String f : fileSet.getDirectoryScanner().getIncludedFiles()) {
            r.put(f, f);
        }
        return r;
    }
}
